<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>同步遍历器的问题</title>
</head>
<body>
    <h1>同步遍历器的问题</h1>

    <script>
        // 同步遍历器无法处理异步操作
        function* syncGenerator() {
            yield 1;
            yield 2;
            yield 3;
        }

        // 同步遍历
        const syncIter = syncGenerator();
        console.log(syncIter.next()); // { value: 1, done: false }
        console.log(syncIter.next()); // { value: 2, done: false }
        console.log(syncIter.next()); // { value: 3, done: false }

        // 尝试处理异步操作（不合适的方式）
        function* problematicGenerator() {
            const result = yield fetch('https://api.example.com/data');
            console.log(result); // result将是一个Promise对象，而不是实际的数据
        }

        // 传统的异步处理方式
        async function traditionalAsync() {
            const urls = [
                'https://api.example.com/1',
                'https://api.example.com/2',
                'https://api.example.com/3'
            ];

            for (const url of urls) {
                const response = await fetch(url);
                const data = await response.json();
                console.log(data);
            }
        }

        // 实际应用示例：读取文件
        class FileReader {
            constructor(files) {
                this.files = files;
                this.index = 0;
            }

            // 同步遍历器无法优雅地处理异步读取
            *[Symbol.iterator]() {
                while (this.index < this.files.length) {
                    // 这里无法使用await
                    yield this.readFile(this.files[this.index++]);
                }
            }

            readFile(file) {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve(`文件${file}的内容`);
                    }, 1000);
                });
            }
        }

        const reader = new FileReader(['a.txt', 'b.txt', 'c.txt']);
        // 这样的遍历会得到Promise对象，而不是实际的文件内容
        for (const content of reader) {
            console.log(content); // Promise { <pending> }
        }
    </script>
</body>
</html>  